package thread;

public class MyPrintABC2 {

    volatile static int next;

    static final Object lockA = new Object();
    static final Object lockB = new Object();
    static final Object lockC = new Object();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (next == 0) {
                    synchronized (lockA) {
                        synchronized (lockB) {
                            synchronized (lockC) {
                                System.out.print("A");
                                next = 1;

                                lockB.notifyAll();
                                lockC.notifyAll();
                            }
                        }
                    }
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                if (next == 1) {
                    synchronized (lockB) {
                        synchronized (lockC) {
                            synchronized (lockA) {
                                System.out.print("B");
                                next++;

                                lockC.notifyAll();
                                lockA.notifyAll();
                            }
                        }
                    }
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                if (next == 2) {
                    synchronized (lockC) {
                        synchronized (lockA) {
                            synchronized (lockB) {
                                System.out.print("C");
                                next = 0;
                                lockA.notifyAll();
                                lockB.notifyAll();
                            }
                        }
                    }
                }
            }
        }).start();

        Thread.sleep(30000L);
    }
}